﻿using Net.Event;
using Net.System;

namespace ServerStressTesting
{
    /// <summary>
    /// Form窗口程序输出帮助类
    /// </summary>
    public class FormDebug : IDebug
    {
        private readonly MyDictionary<string, LogEntity> dic = new();
        public int count = 1000;
        public ListBox listBox;
        /// <summary>
        /// 字体颜色
        /// </summary>
        public Brush BackgroundColor;
        /// <summary>
        /// 日志颜色
        /// </summary>
        public Brush LogColor = Brushes.Blue;
        /// <summary>
        /// 警告颜色
        /// </summary>
        public Brush WarningColor = Brushes.Yellow;
        /// <summary>
        /// 错误颜色
        /// </summary>
        public Brush ErrorColor = Brushes.Red;

        public FormDebug(ListBox listBox, Brush backgroundColor = null)
        {
            if (backgroundColor == null)
                backgroundColor = Brushes.Black;
            this.listBox = listBox;
            this.BackgroundColor = backgroundColor;
            listBox.DrawMode = DrawMode.OwnerDrawFixed;
            listBox.DrawItem += DrawItem;
        }

        public void Output(DateTime time, LogType log, string msg)
        {
            if (dic.Count > count)
            {
                dic.Clear();
                listBox.Items.Clear();
            }
            if (!dic.TryGetValue(log + msg, out var entity))
                dic.TryAdd(log + msg, entity = new LogEntity() { time = time, log = log, msg = msg });
            entity.count++;
            if (entity.row == -1)
            {
                entity.row = listBox.Items.Count;
                listBox.Items.Add(entity);
            }
        }

        public void DrawItem(object sender, DrawItemEventArgs e)
        {
            if (e.Index == -1)
                return;
            var entity = listBox.Items[e.Index] as LogEntity;
            e.DrawBackground();
            e.DrawFocusRectangle();
            var y = e.Bounds.Y;
            var msg = $"[{entity.time.ToString("yyyy-MM-dd HH:mm:ss")}][";
            e.Graphics.DrawString(msg, e.Font, BackgroundColor, 0, y);
            var x = msg.Length * 6;
            msg = $"{entity.log}";
            var color = entity.log == LogType.Log ? LogColor : entity.log == LogType.Warning ? WarningColor : ErrorColor;
            e.Graphics.DrawString(msg, e.Font, color, x, y);
            x += msg.Length * 6;
            msg = entity.msg.Split('\r', '\n')[0];
            if (msg.Length >= byte.MaxValue) //文字过多会报异常
                msg = msg.Substring(0, byte.MaxValue);
            if (entity.count > 1)
                e.Graphics.DrawString($"] ({entity.count}) {msg}", e.Font, BackgroundColor, x, y);
            else
                e.Graphics.DrawString($"] {msg}", e.Font, BackgroundColor, x, y);
        }
    }
}
